package com.example.book.interceptor;

import com.example.book.constant.Constants;
import com.example.book.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2025/7/19
 * Time: 22:03
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    // json 序列化
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // true: 放行     false: 拦截
        log.info("登录拦截.....");
        HttpSession session = request.getSession(false);
        if (session == null ||
                session.getAttribute(Constants.SESSION_USERNAME) == null ||
                !StringUtils.hasLength((String)session.getAttribute(Constants.SESSION_USERNAME))) {
            // 用户未登录
            log.error("用户未登录，进行拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            Result result = Result.unLogin();

            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
            response.setContentType("application/json;charset=utf-8");
            return false;
        }
        log.info("用户登录校验通过");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("执行postHandle.......");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("执行afterCompletion.......");
    }
}
